import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.*;

public class ChatSession extends Thread {

        int             SID;
        Socket  sessionSocket;
        BufferedReader reader = null;
        BufferedWriter writer = null;
       
        public ChatSession ( Socket newConnSocket, int id ) {
                sessionSocket = newConnSocket;
                SID = id;
               
                try {
                        reader = new BufferedReader(new InputStreamReader(sessionSocket.getInputStream()) );
                        writer = new BufferedWriter(new OutputStreamWriter(sessionSocket.getOutputStream()) );
                } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                }

               
                System.out.println();
                System.out.println();
               
                this.start();
               
                BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
                String in = null;
               
                for (;; ) {
                        try {
                                in= stdIn.readLine();
                                //System.out.println( sessionSocket.getLocalAddress().getHostName() + ": " + in );
                                this.sendMsg(in);
                        } catch (IOException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                        }
                }

        }
       
        public void sendMsg ( String message ) throws IOException {
            writer.write( message );
            writer.newLine();
            writer.flush();
        }
       
        public void run() {
                String strBuffer = null;
               
                for (;;) {
                       
                        try {
                                strBuffer = reader.readLine();
                        } catch (IOException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                        }

                        if ( strBuffer != null ) {
                                System.out.println( sessionSocket.getInetAddress().getHostName() + ": " + strBuffer );
                                strBuffer = null;
                        }
                       
                }
        }
       
        private void tearDown() {
               
        }
}

